import React, { Component } from 'react'

export default class App extends Component {
  // 受控：表单的 value 受到了状态的控制（状态不变，value 也变不了）
  state = {
    username: 'dva',
    content: '🧐',
    frame: 'react',
    sex: 'girl',
    hobby: ['apple'],
  }
  handleChange = (e) => {
    this.setState({
      [e.target.name]:
        e.target.type === 'checkbox'
          ? e.target.checked
            ? [...this.state.hobby, e.target.value]
            : this.state.hobby.filter((item) => item !== e.target.value)
          : e.target.value,
    })
  }
  render() {
    // 优化
    const { username, content, frame, sex, hobby } = this.state
    return (
      <ul>
        <li>
          <label htmlFor='username'>用户名</label>
          <input
            name='username'
            id='username'
            value={username}
            onChange={this.handleChange}
          />
        </li>
        <li>
          <label htmlFor='content'>其他信息</label>
          <textarea
            name='content'
            id='content'
            value={content}
            onChange={this.handleChange}
          ></textarea>
        </li>
        <li>
          <label htmlFor='frame'>框架</label>
          <select
            name='frame'
            id='frame'
            value={frame}
            onChange={this.handleChange}
          >
            <option value='vue'>vue</option>
            <option value='react'>react</option>
            <option value='angular'>angular</option>
          </select>
        </li>
        <li>
          <input
            name='sex'
            type='radio'
            id='boy'
            value='boy'
            checked={sex === 'boy'}
            onChange={this.handleChange}
          />
          <label htmlFor='boy'>男</label>
          <input
            name='sex'
            type='radio'
            id='girl'
            value='girl'
            checked={sex === 'girl'}
            onChange={this.handleChange}
          />
          <label htmlFor='girl'>女</label>
          <input
            name='sex'
            type='radio'
            id='unknown'
            value='unknown'
            checked={sex === 'unknown'}
            onChange={this.handleChange}
          />
          <label htmlFor='unknown'>未知</label>
        </li>
        <li>
          <input
            name='hobby'
            type='checkbox'
            id='apple'
            value='apple'
            checked={hobby.includes('apple')}
            onChange={this.handleChange}
          />
          <label htmlFor='apple'>Apple</label>
          <input
            name='hobby'
            type='checkbox'
            id='orange'
            value='orange'
            checked={hobby.includes('orange')}
            onChange={this.handleChange}
          />
          <label htmlFor='orange'>Orange</label>
        </li>
      </ul>
    )
  }
}
